/*
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 */

#include "pi_lib/pi_log.h"
#include <stdio.h>
#include <windows.h>

#define LOG_BUF_LEN 4 * 1024

static const wchar* get_type_str(LogType type)
{
	const wchar *p = NULL;
	switch (type) 
	{
	case LOG_VERBOSE:
		p = L"LOG_VERBOSE";
		break;
	case LOG_DEBUG:
		p = L"LOG_DEBUG";
		break;
	case LOG_INFO:
		p = L"LOG_INFO";
		break;
	case LOG_WARNING:
		p = L"LOG_WARNING";
		break;
	case LOG_ERROR:
		p = L"LOG_ERROR";
		break;
	default:
		break;
	}	
	return p;
}

void pi_log_print(LogType type, const wchar *format, ...)
{
	int tid;
	PiDate date;
	va_list args;
	int formatLen;
	wchar buffer[LOG_BUF_LEN];
	wchar *p = buffer;
	const wchar* typeStr;

	va_start(args, format);
	
	formatLen = 1 + _vscwprintf(format, args);
	if(formatLen > LOG_BUF_LEN)
		p = (wchar *)pi_malloc(formatLen * sizeof(wchar));
	
	vswprintf(p, formatLen, format, args);
	va_end(args);
	
	pi_date_universal (&date);
	tid = GetCurrentThreadId();
	typeStr = get_type_str(type);

	wprintf(L"%04d/%02d/%02d %02d:%02d:%02d, tid: %d, type: %s, info: %s\n", 
		date.year, date.month, date.day, date.hour, date.minute, date.second, tid, typeStr, p);
	
	if(formatLen > LOG_BUF_LEN)
		pi_free(p);
}